package com.kaichaohulian.baocms.adapter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.Spannable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.TextView.BufferType;
import android.widget.Toast;

import com.baidu.mapapi.model.LatLng;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.kaichaohulian.baocms.R;
import com.kaichaohulian.baocms.activity.BaiduMapActivity;
import com.kaichaohulian.baocms.activity.ChatActivity;
import com.kaichaohulian.baocms.activity.ContextMenu;
import com.kaichaohulian.baocms.app.MyApplication;
import com.kaichaohulian.baocms.entity.MessageEntity;
import com.kaichaohulian.baocms.http.Url;
import com.kaichaohulian.baocms.utils.SmileUtils;
import com.kaichaohulian.baocms.utils.StringUtils;
import com.kaichaohulian.baocms.view.FXAlertDialog;
import com.yuntongxun.ecsdk.ECMessage;
import com.yuntongxun.ecsdk.im.ECTextMessageBody;
import com.yuntongxun.ecsdk.im.ECVideoMessageBody;

import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

@SuppressLint({"SdCardPath", "InflateParams"})
public class MessageAdapter extends BaseAdapter {

    private static final int MESSAGE_TYPE_RECV_TXT = 0;
    private static final int MESSAGE_TYPE_SENT_TXT = 1;
    private static final int MESSAGE_TYPE_SENT_IMAGE = 2;
    private static final int MESSAGE_TYPE_SENT_LOCATION = 3;
    private static final int MESSAGE_TYPE_RECV_LOCATION = 4;
    private static final int MESSAGE_TYPE_RECV_IMAGE = 5;
    private static final int MESSAGE_TYPE_SENT_VOICE = 6;
    private static final int MESSAGE_TYPE_RECV_VOICE = 7;
    private static final int MESSAGE_TYPE_SENT_VIDEO = 8;
    private static final int MESSAGE_TYPE_RECV_VIDEO = 9;
    private static final int MESSAGE_TYPE_SENT_FILE = 10;
    private static final int MESSAGE_TYPE_RECV_FILE = 11;
    private static final int MESSAGE_TYPE_SENT_VOICE_CALL = 12;
    private static final int MESSAGE_TYPE_RECV_VOICE_CALL = 13;

    public static final String IMAGE_DIR = "chat/image/";
    public static final String VOICE_DIR = "chat/audio/";
    public static final String VIDEO_DIR = "chat/video";

    private List<MessageEntity> conversation;

    private String username;
    private LayoutInflater inflater;
    private Activity activity;

    private Context context;

    private Map<String, Timer> timers = new Hashtable<String, Timer>();

    public MessageAdapter(Context context, String username, int chatType, List<MessageEntity> conversation) {
        this.username = username;
        this.context = context;
        inflater = LayoutInflater.from(context);
        activity = (Activity) context;
        this.conversation = conversation;
    }

    /**
     * 获取item数
     */
    public int getCount() {
        return conversation.size();
    }

    /**
     * 刷新页面
     */
    public void refresh() {
        notifyDataSetChanged();
    }

    public MessageEntity getItem(int position) {
        return conversation.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    /**
     * 获取item类型
     */
    public int getItemViewType(int position) {
        MessageEntity message = conversation.get(position);
        if (message.getType().equals("TXT")) {
//            if (!message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_VOICE_CALL, false))
            return message.getDirection().equals("RECEIVE") ? MESSAGE_TYPE_RECV_TXT : MESSAGE_TYPE_SENT_TXT;
//            return message.getDirection().equals("RECEIVE" ? MESSAGE_TYPE_RECV_VOICE_CALL
//                    : MESSAGE_TYPE_SENT_VOICE_CALL;
        }
        if (message.getType().equals("IMAGE")) {
            return message.getDirection().equals("RECEIVE") ? MESSAGE_TYPE_RECV_IMAGE
                    : MESSAGE_TYPE_SENT_IMAGE;

        }
        if (message.getType().equals("LOCATION")) {
            return message.getDirection().equals("RECEIVE") ? MESSAGE_TYPE_RECV_LOCATION
                    : MESSAGE_TYPE_SENT_LOCATION;
        }
        if (message.getType().equals("VOICE")) {
            return message.getDirection().equals("RECEIVE") ? MESSAGE_TYPE_RECV_VOICE
                    : MESSAGE_TYPE_SENT_VOICE;
        }
        if (message.getType().equals("VIDEO")) {
            return message.getDirection().equals("RECEIVE") ? MESSAGE_TYPE_RECV_VIDEO
                    : MESSAGE_TYPE_SENT_VIDEO;
        }
        if (message.getType().equals("FILE")) {
            return message.getDirection().equals("RECEIVE") ? MESSAGE_TYPE_RECV_FILE
                    : MESSAGE_TYPE_SENT_FILE;
        }

        return -1;// invalid
    }

    public int getViewTypeCount() {
        return 14;
    }

    @SuppressLint("InflateParams")
    private View createViewByMessage(MessageEntity message, int position) {
        switch (message.getType()) {
            case "LOCATION":
                return message.getDirection().equals("RECEIVE") ? inflater
                        .inflate(R.layout.row_received_location, null) : inflater
                        .inflate(R.layout.row_sent_location, null);
            case "IMAGE":
                return message.getDirection().equals("RECEIVE") ? inflater
                        .inflate(R.layout.row_received_picture, null) : inflater
                        .inflate(R.layout.row_sent_picture, null);
            case "VOICE":
                return message.getDirection().equals("RECEIVE") ? inflater
                        .inflate(R.layout.row_received_voice, null) : inflater
                        .inflate(R.layout.row_sent_voice, null);
            case "VIDEO":
                return message.getDirection().equals("RECEIVE") ? inflater
                        .inflate(R.layout.row_received_video, null) : inflater
                        .inflate(R.layout.row_sent_video, null);
            case "FILE":
                return message.getDirection().equals("RECEIVE") ? inflater
                        .inflate(R.layout.row_received_file, null) : inflater
                        .inflate(R.layout.row_sent_file, null);
            default:
//            // 语音电话
//            if (message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_VOICE_CALL, false))
//                return message.getDirection().equals("RECEIVE" ? inflater.inflate(R.layout.row_received_voice_call, null) : inflater.inflate(R.layout.row_sent_voice_call, null);
                return message.getDirection().equals("RECEIVE") ? inflater
                        .inflate(R.layout.row_received_message, null) : inflater
                        .inflate(R.layout.row_sent_message, null);
        }
    }

    @SuppressLint("NewApi")
    public View getView(final int position, View convertView, ViewGroup parent) {
        final MessageEntity message = getItem(position);
//        ECMessage.Type chatType = message.getType();

        String fromusernick = "0000";
        String fromuseravatar = "0000";

        String msg_dirct = message.getDirection();

        try {
            fromusernick = message.getName();
            fromuseravatar = message.getAvatar();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Log.e("message.getFrom()---->>>>.",message.getFrom());
        if (message.getToId().equals("admin")) {
            convertView = LayoutInflater.from(context).inflate(R.layout.social_chat_admin_item, null);
            TextView timestamp = (TextView) convertView.findViewById(R.id.tv_time);
            TextView tv_content = (TextView) convertView.findViewById(R.id.tv_content);
            timestamp.setText(StringUtils.getStandardDate(Long.parseLong(message.getCreatedTime()) / 1000 + ""));
            Spannable span = SmileUtils.getSmiledText(context, message.getMessage());
            // 设置内容
            tv_content.setText(span, BufferType.SPANNABLE);
            return convertView;
        } else {
            final ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = createViewByMessage(message, position);
                if (message.getType().equals("IMAGE")) {
                    try {
                        holder.iv = ((ImageView) convertView.findViewById(R.id.iv_sendPicture));
                        holder.head_iv = (ImageView) convertView.findViewById(R.id.iv_userhead);
                        holder.tv = (TextView) convertView.findViewById(R.id.percentage);
                        holder.pb = (ProgressBar) convertView.findViewById(R.id.progressBar);
                        holder.staus_iv = (ImageView) convertView.findViewById(R.id.msg_status);
                        holder.tv_userId = (TextView) convertView
                                .findViewById(R.id.tv_userid);
                    } catch (Exception e) {
                    }

                } else if (message.getType().equals("TXT")) {
                    try {
                        holder.pb = (ProgressBar) convertView.findViewById(R.id.pb_sending);
                        holder.staus_iv = (ImageView) convertView.findViewById(R.id.msg_status);
                        holder.head_iv = (ImageView) convertView.findViewById(R.id.iv_userhead);
                        // 这里是文字内容
                        holder.tv = (TextView) convertView.findViewById(R.id.tv_chatcontent);
                        holder.tv_userId = (TextView) convertView.findViewById(R.id.tv_userid);
                    } catch (Exception e) {
                    }
//                    // 语音通话
//                    if (message.getBooleanAttribute(Constant.MESSAGE_ATTR_IS_VOICE_CALL, false)) {
//                        holder.iv = (ImageView) convertView.findViewById(R.id.iv_call_icon);
//                        holder.tv = (TextView) convertView.findViewById(R.id.tv_chatcontent);
//                    }
                } else if (message.getType().equals("VOICE")) {
                    try {
                        holder.iv = ((ImageView) convertView.findViewById(R.id.iv_voice));
                        holder.head_iv = (ImageView) convertView.findViewById(R.id.iv_userhead);
                        holder.tv = (TextView) convertView.findViewById(R.id.tv_length);
                        holder.pb = (ProgressBar) convertView.findViewById(R.id.pb_sending);
                        holder.staus_iv = (ImageView) convertView.findViewById(R.id.msg_status);
                        holder.tv_userId = (TextView) convertView.findViewById(R.id.tv_userid);
                        holder.iv_read_status = (ImageView) convertView.findViewById(R.id.iv_unread_voice);
                    } catch (Exception e) {
                    }
                } else if (message.getType().equals("LOCATION")) {
                    try {
                        holder.head_iv = (ImageView) convertView.findViewById(R.id.iv_userhead);
                        holder.tv = (TextView) convertView.findViewById(R.id.tv_location);
                        holder.pb = (ProgressBar) convertView.findViewById(R.id.pb_sending);
                        holder.staus_iv = (ImageView) convertView.findViewById(R.id.msg_status);
                        holder.tv_userId = (TextView) convertView.findViewById(R.id.tv_userid);
                    } catch (Exception e) {
                    }
                } else if (message.getType().equals("VIDEO")) {
                    try {
                        holder.iv = ((ImageView) convertView.findViewById(R.id.chatting_content_iv));
                        holder.head_iv = (ImageView) convertView.findViewById(R.id.iv_userhead);
                        holder.tv = (TextView) convertView.findViewById(R.id.percentage);
                        holder.pb = (ProgressBar) convertView.findViewById(R.id.progressBar);
                        holder.staus_iv = (ImageView) convertView.findViewById(R.id.msg_status);
                        holder.size = (TextView) convertView.findViewById(R.id.chatting_size_iv);
                        holder.timeLength = (TextView) convertView.findViewById(R.id.chatting_length_iv);
                        holder.playBtn = (ImageView) convertView.findViewById(R.id.chatting_status_btn);
                        holder.container_status_btn = (LinearLayout) convertView.findViewById(R.id.container_status_btn);
                        holder.tv_userId = (TextView) convertView.findViewById(R.id.tv_userid);

                    } catch (Exception e) {
                    }
                } else if (message.getType().equals("FILE")) {
                    try {
                        holder.head_iv = (ImageView) convertView.findViewById(R.id.iv_userhead);
                        holder.tv_file_name = (TextView) convertView.findViewById(R.id.tv_file_name);
                        holder.tv_file_size = (TextView) convertView.findViewById(R.id.tv_file_size);
                        holder.pb = (ProgressBar) convertView.findViewById(R.id.pb_sending);
                        holder.staus_iv = (ImageView) convertView.findViewById(R.id.msg_status);
                        holder.tv_file_download_state = (TextView) convertView.findViewById(R.id.tv_file_state);
                        holder.ll_container = (LinearLayout) convertView.findViewById(R.id.ll_file_container);
                        // 这里是进度值
                        holder.tv = (TextView) convertView.findViewById(R.id.percentage);
                    } catch (Exception e) {
                    }
                    try {
                        holder.tv_userId = (TextView) convertView.findViewById(R.id.tv_userid);
                    } catch (Exception e) {
                    }
                }
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

//            // 群聊时，显示接收的消息的发送人的名称
//            if (chatType == ChatType.GroupChat && message.getDirection().equals("RECEIVE")
//                // demo用username代替nick
//                holder.tv_userId.setText(fromusernick);

            // 如果是发送的消息并且不是群聊消息，显示已读textview
            if (message.getDirection().equals("SEND")) {
                holder.tv_ack = (TextView) convertView.findViewById(R.id.tv_ack);
                holder.tv_delivered = (TextView) convertView.findViewById(R.id.tv_delivered);
                if (holder.tv_ack != null) {
                    if (message.getIsRend() == 1) {
                        if (holder.tv_delivered != null) {
                            holder.tv_delivered.setVisibility(View.INVISIBLE);
                        }
                        holder.tv_ack.setVisibility(View.VISIBLE);
                    } else {
                        holder.tv_ack.setVisibility(View.INVISIBLE);

                        // check and display msg delivered ack status
                        if (holder.tv_delivered != null) {
                            if (message.getIsRend() == 0) {
                                holder.tv_delivered.setVisibility(View.VISIBLE);
                            } else {
                                holder.tv_delivered.setVisibility(View.INVISIBLE);
                            }
                        }
                    }
                }
            } else {
//                 // 如果是文本或者地图消息并且不是group messgae，显示的时候给对方发送已读回执
//                if ((message.getType().equals("TXT") || message.getType().equals("LOCATION") && !message.isAcked && chatType != ChatType.GroupChat) {
//                    // 不是语音通话记录
//                    if (!message.getBooleanAttribute(
//                            Constant.MESSAGE_ATTR_IS_VOICE_CALL, false)) {
//                        try {
//                            EMChatManager.getInstance().ackMessageRead(
//                                    message.getFrom(), message.getMsgId());
//                            // 发送已读回执
//                            message.isAcked = true;
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }
            }

            switch (message.getType()) {
                // 根据消息type显示item
                case "IMAGE": // 图片
                    handleImageMessage(message, holder, position, convertView);
                    break;
                case "TXT": // 文本
//                if (!message.getBody().eq)
                    handleTextMessage(message, holder, position);
//                else
//                    // 语音电话
//                    handleVoiceCallMessage(message, holder, position);
                    break;
                case "LOCATION": // 位置
//                    handleLocationMessage(message, holder, position, convertView);
                    break;
                case "VOICE": // 语音
//                    handleVoiceMessage(message, holder, position, convertView);
                    break;
                case "VIDEO": // 视频
//                    handleVideoMessage(message, holder, position, convertView);
                    break;
                case "FILE": // 一般文件
//                    handleFileMessage(message, holder, position, convertView);
                    break;
                default:
                    // not supported
            }

            if (message.getIsSend().equals("FAILED")) {
                View statusView = convertView.findViewById(R.id.msg_status);
                // 重发按钮点击事件
                statusView.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // 显示重发消息的自定义alertdialog
                        Intent intent = new Intent(activity, FXAlertDialog.class);
                        intent.putExtra("msg", activity.getString(R.string.confirm_resend));
                        intent.putExtra("title", activity.getString(R.string.resend));
                        intent.putExtra("cancel", true);
                        intent.putExtra("position", position);
                        if (message.getType().equals("TXT"))
                            activity.startActivityForResult(intent, ChatActivity.REQUEST_CODE_TEXT);
                        else if (message.getType().equals("VOICE"))
                            activity.startActivityForResult(intent, ChatActivity.REQUEST_CODE_VOICE);
                        else if (message.getType().equals("IMAGE"))
                            activity.startActivityForResult(intent, ChatActivity.REQUEST_CODE_PICTURE);
                        else if (message.getType().equals("LOCATION"))
                            activity.startActivityForResult(intent, ChatActivity.REQUEST_CODE_LOCATION);
                        else if (message.getType().equals("FILE"))
                            activity.startActivityForResult(intent, ChatActivity.REQUEST_CODE_FILE);
                        else if (message.getType().equals("VIDEO"))
                            activity.startActivityForResult(intent, ChatActivity.REQUEST_CODE_VIDEO);
                    }
                });

            } else {
                // 长按头像，移入黑名单
                holder.head_iv.setOnLongClickListener(new OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        Intent intent = new Intent(activity, FXAlertDialog.class);
                        intent.putExtra("msg", "移入到黑名单？");
                        intent.putExtra("cancel", true);
                        intent.putExtra("position", position);
                        activity.startActivityForResult(intent, ChatActivity.REQUEST_CODE_ADD_TO_BLACKLIST);
                        return true;
                    }
                });
            }

            TextView timestamp = (TextView) convertView.findViewById(R.id.timestamp);

            if (position == 0) {
                timestamp.setText(StringUtils.getStandardDate(Long.parseLong(message.getCreatedTime()) / 1000 + ""));
                timestamp.setVisibility(View.VISIBLE);
            } else {
                // 两条消息时间离得如果稍长，显示时间
                if (StringUtils.isCloseEnough(Long.parseLong(message.getCreatedTime()), Long.parseLong(conversation.get(position - 1).getCreatedTime()))) {
                    timestamp.setVisibility(View.GONE);
                } else {
                    timestamp.setText(StringUtils.getStandardDate(Long.parseLong(message.getCreatedTime()) / 1000 + ""));
                    timestamp.setVisibility(View.VISIBLE);
                }
            }
            final String avater = msg_dirct.equals("RECEIVE") ? Url.BASE_URL + fromuseravatar : MyApplication.getInstance().UserInfo.getAvatar();
            Glide.with(parent.getContext()).load(avater).diskCacheStrategy(DiskCacheStrategy.ALL).error(R.mipmap.default_useravatar).into(holder.head_iv);
        }
        return convertView;
    }

    /**
     * 文本消息
     *
     * @param message
     * @param holder
     * @param position
     */
    private void handleTextMessage(final MessageEntity message, ViewHolder holder, final int position) {
        Spannable span = SmileUtils.getSmiledText(context, message.getMessage());
        // 设置内容
        holder.tv.setText(span, BufferType.SPANNABLE);
        // 设置长按事件监听
        holder.tv.setOnLongClickListener(new OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                activity.startActivityForResult((new Intent(activity, ContextMenu.class)).putExtra("position", position).putExtra("type", message.getType()), ChatActivity.REQUEST_CODE_CONTEXT_MENU);
                return true;
            }
        });

        if (message.getDirection().equals("SEND")) {
            switch (message.getIsSend()) {
                case "SUCCESS": // 发送成功
                    holder.pb.setVisibility(View.GONE);
                    holder.staus_iv.setVisibility(View.GONE);
                    break;
                case "FAILED": // 发送失败
                    holder.pb.setVisibility(View.GONE);
                    holder.staus_iv.setVisibility(View.VISIBLE);
                    break;
                case "SENDING": // 发送中
                    holder.pb.setVisibility(View.VISIBLE);
                    holder.staus_iv.setVisibility(View.GONE);
                    break;
                default:
                    // 发送消息
                    sendMsgInBackground(message, holder);
            }
        }
    }

    /**
     * 语音通话记录
     *
     * @param message
     * @param holder
     * @param position
     */
    private void handleVoiceCallMessage(ECMessage message, ViewHolder holder,
                                        final int position) {
        ECTextMessageBody txtBody = (ECTextMessageBody) message.getBody();
        holder.tv.setText(txtBody.getMessage());

    }

    /**
     * 图片消息
     *
     * @param message
     * @param holder
     * @param position
     * @param convertView
     */
    private void handleImageMessage(final MessageEntity message, final ViewHolder holder, final int position, View convertView) {
        holder.pb.setTag(position);
        // holder.iv.setOnLongClickListener(new OnLongClickListener() {
        // @Override
        // public boolean onLongClick(View v) {
        // activity.startActivityForResult((new Intent(activity,
        // ContextMenu.class)).putExtra("position", position)
        // .putExtra("type", EMMessage.Type.IMAGE.ordinal()),
        // ChatActivity.REQUEST_CODE_CONTEXT_MENU);
        // return true;
        // }
        // });

        // 接收方向的消息
        if (message.getDirection().equals("RECEIVE")) {
            holder.pb.setVisibility(View.GONE);
            holder.tv.setVisibility(View.GONE);
            holder.iv.setImageResource(R.mipmap.default_image);
            return;
        }

        // 发送的消息
        showImageView(holder.iv, message.getMessage(), message);

        switch (message.getIsSend()) {
            case "SUCCESS":
                holder.pb.setVisibility(View.GONE);
                holder.tv.setVisibility(View.GONE);
                holder.staus_iv.setVisibility(View.GONE);
                break;
            case "FAILED":
                holder.pb.setVisibility(View.GONE);
                holder.tv.setVisibility(View.GONE);
                holder.staus_iv.setVisibility(View.VISIBLE);
                break;
            case "SENDING":
                holder.staus_iv.setVisibility(View.GONE);
                holder.pb.setVisibility(View.VISIBLE);
                holder.tv.setVisibility(View.VISIBLE);
                if (timers.containsKey(message.getMsgId()))
                    return;
                // set a timer
                final Timer timer = new Timer();
                timers.put(message.getMsgId(), timer);
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        activity.runOnUiThread(new Runnable() {
                            public void run() {
                                holder.pb.setVisibility(View.VISIBLE);
                                holder.tv.setVisibility(View.VISIBLE);
                                holder.tv.setText("0%");
                                if (message.getIsSend().equals(ECMessage.MessageStatus.SUCCESS)) {
                                    holder.pb.setVisibility(View.GONE);
                                    holder.tv.setVisibility(View.GONE);
                                    // message.setSendingStatus(Message.SENDING_STATUS_SUCCESS);
                                    timer.cancel();
                                } else if (message.getIsSend().equals(ECMessage.MessageStatus.FAILED)) {
                                    holder.pb.setVisibility(View.GONE);
                                    holder.tv.setVisibility(View.GONE);
                                    // message.setSendingStatus(Message.SENDING_STATUS_FAIL);
                                    // message.setProgress(0);
                                    holder.staus_iv.setVisibility(View.VISIBLE);
                                    Toast.makeText(
                                            activity,
                                            activity.getString(R.string.send_fail)
                                                    + activity
                                                    .getString(R.string.connect_failuer_toast),
                                            Toast.LENGTH_LONG).show();
                                    timer.cancel();
                                }

                            }
                        });

                    }
                }, 0, 500);
                break;
            default:
                sendPictureMessage(message, holder);
        }
    }

    /**
     * 视频消息
     *
     * @param message
     * @param holder
     * @param position
     * @param convertView
     */
    private void handleVideoMessage(final ECMessage message, final ViewHolder holder, final int position, View convertView) {

        ECVideoMessageBody videoBody = (ECVideoMessageBody) message.getBody();
        // final File image=new File(PathUtil.getInstance().getVideoPath(),
        // videoBody.getFileName());
        String localThumb = videoBody.getLocalThumb();

        // holder.iv.setOnLongClickListener(new OnLongClickListener() {
        //
        // @Override
        // public boolean onLongClick(View v) {
        // activity.startActivityForResult(new Intent(activity,
        // ContextMenu.class).putExtra("position", position)
        // .putExtra("type", EMMessage.Type.VIDEO.ordinal()),
        // ChatActivity.REQUEST_CODE_CONTEXT_MENU);
        // return true;
        // }
        // });

        if (localThumb != null) {
            showVideoThumbView(localThumb, holder.iv, videoBody.getThumbnailUrl(), message);
        }
        if (videoBody.getLength() > 0) {
            String time = "60";
            holder.timeLength.setText(time);
        }
        holder.playBtn.setImageResource(R.mipmap.video_download_btn_nor);

//        if (message.getDirection().equals("RECEIVE") {
//            if (videoBody.getLength() > 0) {
//                String size = TextFormater.getDataSize(videoBody.getLength());
//                holder.size.setText(size);
//            }
//        } else {
//            if (videoBody.getLocalUrl() != null
//                    && new File(videoBody.getLocalUrl()).exists()) {
//                String size = TextFormater.getDataSize(new File(videoBody
//                        .getLocalUrl()).length());
//                holder.size.setText(size);
//            }
//        }
//
//        if (message.getDirection().equals("RECEIVE") {
//
//            // System.err.println("it is receive msg");
//            if (message.getDirection().equals(ECMessage.Direction.INPROGRESS) {
//                // System.err.println("!!!! back receive");
//                holder.iv.setImageResource(R.mipmap.default_image);
//                showDownloadImageProgress(message, holder);
//
//            } else {
//                // System.err.println("!!!! not back receive, show image directly");
//                holder.iv.setImageResource(R.mipmap.default_image);
//                if (localThumb != null) {
//                    showVideoThumbView(localThumb, holder.iv,
//                            videoBody.getThumbnailUrl(), message);
//                }
//
//            }
//
//            return;
//        }
//        holder.pb.setTag(position);
//
//        // until here ,deal with send video msg
//        switch (message.getMsgStatus()) {
//        case SUCCESS:
//            holder.pb.setVisibility(View.GONE);
//            holder.staus_iv.setVisibility(View.GONE);
//            holder.tv.setVisibility(View.GONE);
//            break;
//            case FAILED:
//            holder.pb.setVisibility(View.GONE);
//            holder.tv.setVisibility(View.GONE);
//            holder.staus_iv.setVisibility(View.VISIBLE);
//            break;
//            case SENDING:
//            if (timers.containsKey(message.getMsgId()))
//                return;
//            // set a timer
//            final Timer timer = new Timer();
//            timers.put(message.getMsgId(), timer);
//            timer.schedule(new TimerTask() {
//
//                @Override
//                public void run() {
//                    activity.runOnUiThread(new Runnable() {
//
//                        @Override
//                        public void run() {
//                            holder.pb.setVisibility(View.VISIBLE);
//                            holder.tv.setVisibility(View.VISIBLE);
//                            holder.tv.setText(message.progress + "%");
//                            if (message.getIsSend().equals(ECMessage.MessageStatus.SUCCESS) {
//                                holder.pb.setVisibility(View.GONE);
//                                holder.tv.setVisibility(View.GONE);
//                                // message.setSendingStatus(Message.SENDING_STATUS_SUCCESS);
//                                timer.cancel();
//                            } else if (message.getIsSend().equals(ECMessage.MessageStatus.FAILED) {
//                                holder.pb.setVisibility(View.GONE);
//                                holder.tv.setVisibility(View.GONE);
//                                // message.setSendingStatus(Message.SENDING_STATUS_FAIL);
//                                // message.setProgress(0);
//                                holder.staus_iv.setVisibility(View.VISIBLE);
//                                Toast.makeText(
//                                        activity,
//                                        activity.getString(R.string.send_fail)
//                                                + activity
//                                                        .getString(R.string.connect_failuer_toast),
//                                        Toast.LENGTH_LONG).show();
//                                timer.cancel();
//                            }
//
//                        }
//                    });
//
//                }
//            }, 0, 500);
//            break;
//        default:
//            // sendMsgInBackground(message, holder);
//            sendPictureMessage(message, holder);
//
//        }

    }

    /**
     * 语音消息
     *
     * @param message
     * @param holder
     * @param position
     * @param convertView
     */
    private void handleVoiceMessage(final ECMessage message,
                                    final ViewHolder holder, final int position, View convertView) {
//        ECVoiceMessageBody voiceBody = (ECVoiceMessageBody) message.getBody();
//        holder.tv.setText(voiceBody.getLength() + "\"");
//        holder.iv.setOnClickListener(new VoicePlayClickListener(message,holder.iv, holder.iv_read_status, this, activity, username));
//        // holder.iv.setOnLongClickListener(new OnLongClickListener() {
//        // @Override
//        // public boolean onLongClick(View v) {
//        // activity.startActivityForResult((new Intent(activity,
//        // ContextMenu.class)).putExtra("position", position)
//        // .putExtra("type", EMMessage.Type.VOICE.ordinal()),
//        // ChatActivity.REQUEST_CODE_CONTEXT_MENU);
//        // return true;
//        // }
//        // });
//        if (((ChatActivity) activity).playMsgId != null && ((ChatActivity) activity).playMsgId.equals(message.getMsgId()) && VoicePlayClickListener.isPlaying) {
//            AnimationDrawable voiceAnimation;
//            if (message.getDirection().equals("RECEIVE") {
//                holder.iv.setImageResource(R.drawable.voice_from_icon);
//            } else {
//                holder.iv.setImageResource(R.drawable.voice_to_icon);
//            }
//            voiceAnimation = (AnimationDrawable) holder.iv.getDrawable();
//            voiceAnimation.start();
//        } else {
//            if (message.getDirection().equals("RECEIVE") {
//                holder.iv.setImageResource(R.mipmap.chatfrom_voice_playing);
//            } else {
//                holder.iv.setImageResource(R.mipmap.chatto_voice_playing);
//            }
//        }
//
//        if (message.getDirection().equals("RECEIVE") {
//            if (message.isMultimediaBody()) {
//                // 隐藏语音未听标志
//                holder.iv_read_status.setVisibility(View.INVISIBLE);
//            } else {
//                holder.iv_read_status.setVisibility(View.VISIBLE);
//            }
//            System.err.println("it is receive msg");
//            if (message.getIsSend().equals(ECMessage.MessageStatus.SENDING) {
//                holder.pb.setVisibility(View.VISIBLE);
//                System.err.println("!!!! back receive");
//                ((FileMessageBody) message.getBody())
//                        .setDownloadCallback(new EMCallBack() {
//
//                            @Override
//                            public void onSuccess() {
//                                activity.runOnUiThread(new Runnable() {
//
//                                    @Override
//                                    public void run() {
//                                        holder.pb.setVisibility(View.INVISIBLE);
//                                        notifyDataSetChanged();
//                                    }
//                                });
//
//                            }
//
//                            @Override
//                            public void onProgress(int progress, String status) {
//                            }
//
//                            @Override
//                            public void onError(int code, String message) {
//                                activity.runOnUiThread(new Runnable() {
//
//                                    @Override
//                                    public void run() {
//                                        holder.pb.setVisibility(View.INVISIBLE);
//                                    }
//                                });
//
//                            }
//                        });
//
//            } else {
//                holder.pb.setVisibility(View.INVISIBLE);
//
//            }
//            return;
//        }
//
//        // until here, deal with send voice msg
//        switch (message.getMsgStatus()) {
//        case SUCCESS:
//            holder.pb.setVisibility(View.GONE);
//            holder.staus_iv.setVisibility(View.GONE);
//            break;
//            case FAILED:
//            holder.pb.setVisibility(View.GONE);
//            holder.staus_iv.setVisibility(View.VISIBLE);
//            break;
//            case SENDING:
//            holder.pb.setVisibility(View.VISIBLE);
//            holder.staus_iv.setVisibility(View.GONE);
//            break;
//        default:
//            sendMsgInBackground(message, holder);
//        }
    }

    /**
     * 文件消息
     *
     * @param message
     * @param holder
     * @param position
     * @param convertView
     */
    private void handleFileMessage(final ECMessage message,
                                   final ViewHolder holder, int position, View convertView) {
//        final ECFileMessageBody fileMessageBody = (ECFileMessageBody) message
//                .getBody();
//        final String filePath = fileMessageBody.getLocalUrl();
//        holder.tv_file_name.setText(fileMessageBody.getFileName());
//        holder.tv_file_size.setText(TextFormater.getDataSize(fileMessageBody
//                .getFileSize()));
//        holder.ll_container.setOnClickListener(new OnClickListener() {
//
//            @Override
//            public void onClick(View view) {
//                File file = new File(filePath);
//                if (file != null && file.exists()) {
//                    // 文件存在，直接打开
//                    FileUtils.openFile(file, (Activity) context);
//                } else {
//                    // 下载
//                    context.startActivity(new Intent(context,
//                            ShowNormalFileActivity.class).putExtra("msgbody",
//                            fileMessageBody));
//                }
//                if (message.getDirection().equals("RECEIVE"
//                        && !message.isAcked) {
//                    try {
//                        EMChatManager.getInstance().ackMessageRead(
//                                message.getFrom(), message.getMsgId());
//                        message.isAcked = true;
//                    } catch (EaseMobException e) {
//                        // TODO Auto-generated catch block
//                        e.printStackTrace();
//                    }
//                }
//            }
//        });
//
//        if (message.getDirection().equals("RECEIVE") { // 接收的消息
//            System.err.println("it is receive msg");
//            File file = new File(filePath);
//            if (file != null && file.exists()) {
//                holder.tv_file_download_state.setText("已下载");
//            } else {
//                holder.tv_file_download_state.setText("未下载");
//            }
//            return;
//        }
//
//        // until here, deal with send voice msg
//        switch (message.getMsgStatus()) {
//        case SUCCESS:
//            holder.pb.setVisibility(View.INVISIBLE);
//            holder.tv.setVisibility(View.INVISIBLE);
//            holder.staus_iv.setVisibility(View.INVISIBLE);
//            break;
//            case FAILED:
//            holder.pb.setVisibility(View.INVISIBLE);
//            holder.tv.setVisibility(View.INVISIBLE);
//            holder.staus_iv.setVisibility(View.VISIBLE);
//            break;
//            case SENDING:
//            if (timers.containsKey(message.getMsgId()))
//                return;
//            // set a timer
//            final Timer timer = new Timer();
//            timers.put(message.getMsgId(), timer);
//            timer.schedule(new TimerTask() {
//
//                @Override
//                public void run() {
//                    activity.runOnUiThread(new Runnable() {
//
//                        @Override
//                        public void run() {
//                            holder.pb.setVisibility(View.VISIBLE);
//                            holder.tv.setVisibility(View.VISIBLE);
//                            holder.tv.setText(message.progress + "%");
//                            if (message.getIsSend().equals(ECMessage.MessageStatus.SUCCESS) {
//                                holder.pb.setVisibility(View.INVISIBLE);
//                                holder.tv.setVisibility(View.INVISIBLE);
//                                timer.cancel();
//                            } else if (message.getIsSend().equals(ECMessage.MessageStatus.FAILED) {
//                                holder.pb.setVisibility(View.INVISIBLE);
//                                holder.tv.setVisibility(View.INVISIBLE);
//                                holder.staus_iv.setVisibility(View.VISIBLE);
//                                Toast.makeText(
//                                        activity,
//                                        activity.getString(R.string.send_fail)
//                                                + activity
//                                                        .getString(R.string.connect_failuer_toast),
//                                        Toast.LENGTH_LONG).show();
//                                timer.cancel();
//                            }
//
//                        }
//                    });
//
//                }
//            }, 0, 500);
//            break;
//        default:
//            // 发送消息
//            sendMsgInBackground(message, holder);
//        }

    }

    /**
     * 处理位置消息
     *
     * @param message
     * @param holder
     * @param position
     * @param convertView
     */
    private void handleLocationMessage(final ECMessage message,
                                       final ViewHolder holder, final int position, View convertView) {
//        TextView locationView = ((TextView) convertView
//                .findViewById(R.id.tv_location));
//        ECVoiceMessageBody locBody = (ECVoiceMessageBody) message.getBody();
//        locationView.setText(locBody.getAddress());
//        LatLng loc = new LatLng(locBody.getLatitude(), locBody.getLongitude());
//        locationView.setOnClickListener(new MapClickListener(loc, locBody
//                .getAddress()));
//        // locationView.setOnLongClickListener(new OnLongClickListener() {
//        // @Override
//        // public boolean onLongClick(View v) {
//        // activity.startActivityForResult((new Intent(activity,
//        // ContextMenu.class)).putExtra("position", position)
//        // .putExtra("type", EMMessage.Type.LOCATION.ordinal()),
//        // ChatActivity.REQUEST_CODE_CONTEXT_MENU);
//        // return false;
//        // }
//        // });
//
//        if (message.getDirection().equals("RECEIVE") {
//            return;
//        }
//        // deal with send message
//        switch (message.getMsgStatus()) {
//        case SUCCESS:
//            holder.pb.setVisibility(View.GONE);
//            holder.staus_iv.setVisibility(View.GONE);
//            break;
//            case FAILED:
//            holder.pb.setVisibility(View.GONE);
//            holder.staus_iv.setVisibility(View.VISIBLE);
//            break;
//            case SENDING:
//            holder.pb.setVisibility(View.VISIBLE);
//            break;
//        default:
//            sendMsgInBackground(message, holder);
//        }
    }

    /**
     * 发送消息
     *
     * @param message
     * @param holder
     */
    public void sendMsgInBackground(final MessageEntity message, final ViewHolder holder) {

    }

    /*
     * chat sdk will automatic download thumbnail image for the image message we
     * need to register callback show the download progress
     */
    private void showDownloadImageProgress(final ECMessage message,
                                           final ViewHolder holder) {
//        System.err.println("!!! show download image progress");
//        // final ImageMessageBody msgbody = (ImageMessageBody)
//        // message.getBody();
//        final FileMessageBody msgbody = (FileMessageBody) message.getBody();
//        if (holder.pb != null)
//            holder.pb.setVisibility(View.VISIBLE);
//        if (holder.tv != null)
//            holder.tv.setVisibility(View.VISIBLE);
//
//        msgbody.setDownloadCallback(new EMCallBack() {
//
//            @Override
//            public void onSuccess() {
//                activity.runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        // message.setBackReceive(false);
//                        if (message.getType().equals(EMMessage.Type.IMAGE) {
//                            holder.pb.setVisibility(View.GONE);
//                            holder.tv.setVisibility(View.GONE);
//                        }
//                        notifyDataSetChanged();
//                    }
//                });
//            }
//
//            @Override
//            public void onError(int code, String message) {
//
//            }
//
//            @Override
//            public void onProgress(final int progress, String status) {
//                if (message.getType().equals("IMAGE") {
//                    activity.runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            holder.tv.setText(progress + "%");
//
//                        }
//                    });
//                }
//
//            }
//
//        });
    }

    /*
     * send message with new sdk
     */
    private void sendPictureMessage(final MessageEntity message, final ViewHolder holder) {
//        try {
//            String to = message.getTo();
//
//            // before send, update ui
//            holder.staus_iv.setVisibility(View.GONE);
//            holder.pb.setVisibility(View.VISIBLE);
//            holder.tv.setVisibility(View.VISIBLE);
//            holder.tv.setText("0%");
//
//            final long start = System.currentTimeMillis();
//            // if (chatType == ChatActivity.CHATTYPE_SINGLE) {
//            EMChatManager.getInstance().sendMessage(message, new EMCallBack() {
//
//                @Override
//                public void onSuccess() {
//                    Log.d(TAG, "send image message successfully");
//
//                    activity.runOnUiThread(new Runnable() {
//                        public void run() {
//                            // send success
//                            holder.pb.setVisibility(View.GONE);
//                            holder.tv.setVisibility(View.GONE);
//                        }
//                    });
//                }
//
//                @Override
//                public void onError(int code, String error) {
//
//                    activity.runOnUiThread(new Runnable() {
//                        public void run() {
//                            holder.pb.setVisibility(View.GONE);
//                            holder.tv.setVisibility(View.GONE);
//                            // message.setSendingStatus(Message.SENDING_STATUS_FAIL);
//                            holder.staus_iv.setVisibility(View.VISIBLE);
//                            Toast.makeText(
//                                    activity,
//                                    activity.getString(R.string.send_fail)
//                                            + activity
//                                                    .getString(R.string.connect_failuer_toast),
//                                    Toast.LENGTH_LONG).show();
//                        }
//                    });
//                }
//
//                @Override
//                public void onProgress(final int progress, String status) {
//                    activity.runOnUiThread(new Runnable() {
//                        public void run() {
//                            holder.tv.setText(progress + "%");
//                        }
//                    });
//                }
//
//            });
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    /**
     * 更新ui上消息发送状态
     *
     * @param message
     * @param holder
     */
    private void updateSendedView(final MessageEntity message,
                                  final ViewHolder holder) {
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // send success
                if (message.getType().equals("VIDEO")) {
                    holder.tv.setVisibility(View.GONE);
                }
                if (message.getIsSend().equals(ECMessage.MessageStatus.SUCCESS)) {
                    // if (message.getType().equals(EMMessage.Type.FILE) {
                    // holder.pb.setVisibility(View.INVISIBLE);
                    // holder.staus_iv.setVisibility(View.INVISIBLE);
                    // } else {
                    // holder.pb.setVisibility(View.GONE);
                    // holder.staus_iv.setVisibility(View.GONE);
                    // }

                } else if (message.getIsSend().equals(ECMessage.MessageStatus.FAILED)) {
                    // if (message.getType().equals(EMMessage.Type.FILE) {
                    // holder.pb.setVisibility(View.INVISIBLE);
                    // } else {
                    // holder.pb.setVisibility(View.GONE);
                    // }
                    // holder.staus_iv.setVisibility(View.VISIBLE);
                    Toast.makeText(
                            activity,
                            activity.getString(R.string.send_fail)
                                    + activity
                                    .getString(R.string.connect_failuer_toast),
                            Toast.LENGTH_LONG).show();
                }

                notifyDataSetChanged();
            }
        });
    }

    /**
     * load image into image view
     *
     * @param Path
     * @param iv
     * @return the image exists or not
     */
    private boolean showImageView(final ImageView iv, final String Path, final MessageEntity message) {
        Glide.with(context).load(Path).diskCacheStrategy(DiskCacheStrategy.ALL).into(iv);
        return false;
    }

    /**
     * 展示视频缩略图
     *
     * @param localThumb   本地缩略图路径
     * @param iv
     * @param thumbnailUrl 远程缩略图路径
     * @param message
     */
    private void showVideoThumbView(String localThumb, ImageView iv,
                                    String thumbnailUrl, final ECMessage message) {
//        // first check if the thumbnail image already loaded into cache
//        Bitmap bitmap = ImageCache.getInstance().get(localThumb);
//        if (bitmap != null) {
//            // thumbnail image is already loaded, reuse the drawable
//            iv.setImageBitmap(bitmap);
//            iv.setClickable(true);
//            iv.setOnClickListener(new OnClickListener() {
//
//                @Override
//                public void onClick(View v) {
//                    VideoMessageBody videoBody = (VideoMessageBody) message.getBody();
//                    System.err.println("video view is on click");
//                    Intent intent = new Intent(activity, ShowVideoActivity.class);
//                    intent.putExtra("localpath", videoBody.getLocalUrl());
//                    intent.putExtra("secret", videoBody.getSecret());
//                    intent.putExtra("remotepath", videoBody.getRemoteUrl());
//                    if (message != null
//                            && message.getDirection().equals("RECEIVE"
//                            && !message.isAcked
//                            && message.getChatType() != ChatType.GroupChat) {
//                        message.isAcked = true;
//                        try {
//                            EMChatManager.getInstance().ackMessageRead(
//                                    message.getFrom(), message.getMsgId());
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                    }
//                    activity.startActivity(intent);
//
//                }
//            });
//
//        } else {
//            new LoadVideoImageTask().execute(localThumb, thumbnailUrl, iv,
//                    activity, message, this);
//        }

    }

    public static class ViewHolder {
        ImageView iv;
        TextView tv;
        ProgressBar pb;
        ImageView staus_iv;
        ImageView head_iv;
        TextView tv_userId;
        ImageView playBtn;
        TextView timeLength;
        TextView size;
        LinearLayout container_status_btn;
        LinearLayout ll_container;
        ImageView iv_read_status;
        // 显示已读回执状态
        TextView tv_ack;
        // 显示送达回执状态
        TextView tv_delivered;

        TextView tv_file_name;
        TextView tv_file_size;
        TextView tv_file_download_state;
    }

    /*
     * 点击地图消息listener
     */
    class MapClickListener implements OnClickListener {

        LatLng location;
        String address;

        public MapClickListener(LatLng loc, String address) {
            location = loc;
            this.address = address;
        }

        @Override
        public void onClick(View v) {
            Intent intent;
            intent = new Intent(context, BaiduMapActivity.class);
            intent.putExtra("latitude", location.latitude);
            intent.putExtra("longitude", location.longitude);
            intent.putExtra("address", address);
            activity.startActivity(intent);
        }
    }

}